<template>
    <div class="sales-product-container">
        <h2>发票登记</h2>
        <br />

        <!-- 查询表单 -->
        <el-form :model="searchForm" label-width="auto" class="sales-product-form">
            <div class="form-row">
                <el-form-item label="单据日期：" prop="dateRange">
                    <el-date-picker v-model="tempDateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 340px;"
                        @change="handleDateRangeChange" />
                </el-form-item>
                <el-form-item label="单据编号：" prop="invoiceNo">
                    <el-input v-model="searchForm.procurement_code" placeholder="单号" style="width: 240px;" />
                </el-form-item>
                <el-form-item label="供应商">
                    <el-input v-model="selectedSupplier.SupplierName" placeholder="选择供应商(必选)" clearable disabled
                        style="width: 200px;">
                        <template #append>
                            <el-button :icon="Search" @click="supplierDialog.open()" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </div>
        </el-form>

        <!-- 操作按钮：导出、开票记录等 -->
        <div class="form-actions">
            <el-button type="primary" @click="handleInvoiceRegister">发票登记</el-button>
            <el-button @click="handleOpenRecord">开票记录</el-button>
            <el-button @click="handleExport">导出</el-button>
            <el-button>打印</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filterTableData" border style="width: 100%;height: 300px;" :summary-method="getSummary"
            show-summary @selection-change="handelSelectionChange" row-key="procurement_code"
            :row-class-name="getRefundRowClass">
            <el-table-column type="selection" width="55" reserve-selection />
            <el-table-column prop="procurement_date" label="单据日期" width="160" />
            <el-table-column prop="procurement_code" label="单据编号" width="160" />
            <el-table-column prop="procurementOrder_code" label="关联购货订单号" width="160" />
            <el-table-column prop="supplier_name" label="供应商" width="180" />
            <el-table-column prop="buyer" label="源制单人" width="120" />
            <el-table-column prop="procurement_quantity" label="数量" width="100" />
            <el-table-column prop="buy_amount" label="金额" width="120" />
            <el-table-column prop="tax_amount" label="税额" width="120" />
            <el-table-column prop="written_off_amount" label="已付款(已核销)" width="120" />
            <el-table-column prop="pay_status" label="付款状态" width="120">
                <template #default="{ row }">
                    {{ getPayStatus(row) }}
                </template>
            </el-table-column>
            <el-table-column prop="procurement_amount" label="价税合计" width="120" />
            <el-table-column prop="alreadyOpen_amount" label="已开票金额" width="130">
                <template #default="{ row }">
                    {{ row.alreadyOpen_amount }}
                </template>
            </el-table-column>
            <el-table-column prop="noOpen_amount" label="未开票金额" width="130">
                <template #default="{ row }">
                    {{ row.noOpen_amount }}
                </template>
            </el-table-column>
            <el-table-column prop="thisOpen_amount" label="*本次开票金额" width="140">
                <template #default="{ row }">
                    <el-input-number v-model="row.thisOpen_amount" size="small" :controls="false" style="width: 80px;"
                        :min="0" :max="row.noOpen_amount" placeholder="0.00" :precision="2"
                        @change="changeAmount"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="整单备注" min-width="180">
                <template #default="{ row }">
                    <el-input v-model="row.remark" style="width: 140px;" size="small"></el-input>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="float: right; padding-top: 20px;">
            <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total"
                :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum" @current-change="changePage" />
        </div>
        <div style="clear: both;"></div>
    </div>

    <!-- 底部开票信息输入区 -->
    <div class="footer-form">
        <el-form :inline="true" label-width="auto" style="margin-top: 16px;">
            <div class="form-row" style="gap: 16px; align-items: center;">
                <el-form-item label="开票日期：" required>
                    <el-date-picker v-model="invoiceForm.invoice_date" type="date" placeholder="选择日期"
                        style="width: 200px;" />
                </el-form-item>

                <el-form-item label="发票号：" required>
                    <el-input v-model="invoiceForm.invoice_num" placeholder="请输入发票号" style="width: 200px;" />
                </el-form-item>

                <el-form-item label="发票金额：">
                    <el-input v-model="invoiceForm.invoice_amount" placeholder="0.00" style="width: 200px;" disabled />
                </el-form-item>


                <el-form-item label="开票备注：">
                    <el-input v-model="invoiceForm.remark" placeholder="请输入备注" style="width: 200px;" />
                </el-form-item>
            </div>
        </el-form>
    </div>

    <!-- 供应商对话框 -->
    <SupplierDialog ref="supplierDialog" :supplier-list="SupplierList" @confirm="handleSupplierConfirm" />
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import SupplierDialog from '@/util/SupplierDialog.vue'
import axios from 'axios'

const route = useRouter()
// 分页信息
const pageInfo = reactive({
    total: 10,
    pageSize: 5,
    pageNum: 1,
})
// 设置退款行的样式
const getRefundRowClass = ({ row }) => {
    return row.isRefund === 1 ? 'refund-row' : ''
}
//设置付款状态

const getPayStatus = (row) => {
    if (row.isRefund == 0) {
        const status = row.pay_status
        const statusMap = {
            '0': '未付款',
            '1': '部分付款',
            '2': '全部付款',
        }
        return statusMap[status] || ''
    }
    else {
        row.pay_status = parseInt(row.refund_status) + 3
        const status = row.refund_status
        const statusMap = {
            '0': '未退款',
            '1': '部分退款',
            '2': '全部退款',
        }
        return statusMap[status] || ''
    }
}

// 查询表单数据
const searchForm = reactive({
    start_Date: '',
    end_Date: '',
    procurement_code: '',
    supplier_code: '',
    supplier_name: '',
    written_off_amount: 0
})

onMounted(() => {
    getTableData()

})
//处理供应商选择

// 对话框引用
const supplierDialog = ref(null);
// 选择的供应商
const selectedSupplier = reactive({
    SupplierName: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    totalDebt: 0
});

// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
    if (supplier) {
        Object.assign(selectedSupplier, supplier);
        ElMessage.success(`已选择供应商：${supplier.SupplierName || '空选'}`);
    } else {
        // 如果 supplier 是 null 或 undefined，清空 selectedSupplier
        Object.keys(selectedSupplier).forEach(key => {
            selectedSupplier[key] = '';
        });
        ElMessage.success('已选择空选');
    }
    searchForm.supplier_code = supplier?.SupplierCode || ''
    searchForm.supplier_name = supplier?.SupplierName || ''
};


// 临时存储日期范围
const tempDateRange = ref([])

// 日期范围变化处理
const handleDateRangeChange = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        searchForm.start_Date = dateRange[0]
        searchForm.end_Date = dateRange[1]
    } else {
        searchForm.start_Date = ''
        searchForm.end_Date = ''
    }
}
// 表格数据
const tableData = ref([])

const loading = ref(false)

//获取表格数据
const getTableData = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            isResource: 1,
            ...searchForm
        }
        const res = await axios.get('/lxw/selectMainProcurementPage', { params })
        if (res.data.code == 5200) {
            const list = res.data.procurementPageInfo.list || []

            console.log('发票记录数据',list)

            // 并行获取所有行的开票金额
            const enhancedList = await Promise.all(
                list.map(async (item) => {
                    const alreadyOpenAmount = await getAlreadyOpen_amount(item.procurement_code)
                    const totalAmount = parseFloat(item.procurement_amount) || 0
                    const noOpenAmount = totalAmount - parseFloat(item.written_off_amount)

                    return {
                        ...item,
                        alreadyOpen_amount: alreadyOpenAmount.toFixed(2),
                        noOpen_amount: noOpenAmount > 0 ? noOpenAmount.toFixed(2) : 0,
                        thisOpen_amount: 0,
                        remark: item.remark || '',
                        buyer: item.created_by
                    }
                })
            )

            tableData.value = enhancedList
            console.log("tableData", tableData)
            pageInfo.pageNum = res.data.procurementPageInfo.pageNum
            pageInfo.pageSize = res.data.procurementPageInfo.pageSize
            pageInfo.total = res.data.procurementPageInfo.total

            calculateTotalInvoiceAmount()
        }
    } catch (error) {
        ElMessage.error("获取数据失败", error)
    } finally {
        loading.value = false
    }
}

// 过滤表格中未开发票金额大于0并且已付款的数据
const filterTableData = computed(() => {
    return (tableData.value || []).filter(item => {
        const noOpenAmount = parseFloat(item.noOpen_amount) || 0
        const written_off_amount = parseFloat(item.written_off_amount) || 0
        return noOpenAmount > 0 && written_off_amount > 0
    })
})
//获取已发票金额
const getAlreadyOpen_amount = async (procurement_code) => {
    try {
        const res = await axios.get('/lxw/getAlreadyOpen_amountByCode', {
            params: {
                procurement_code: procurement_code
            }
        }
        )
        console.log("num2133", res.data.num)
        return res.data.num || 0.00
    } catch (error) {
        console.error('获取已开票金额失败:', error)
        return 0.00
    }
}

// 开票表单
const invoiceForm = reactive({
    invoice_date: new Date,
    invoice_num: '',
    invoice_amount: 0,
    invoice_title: '',
    remark: '',
})

// 查询
const handleSearch = () => {
    console.log('查询条件:', searchForm)
    getTableData()
}

// 分页切换
const changePage = (pageNum) => {
    pageInfo.pageNum = pageNum
    console.log('当前页:', pageNum)
    getTableData()
}


//表格数据选择变换
const selectedRows = ref([])
const handelSelectionChange = (selection) => {
    selectedRows.value = selection
    console.log("选中的行数据", selectedRows.value)
    calculateTotalInvoiceAmount()
}


const changeAmount = () => {
    calculateTotalInvoiceAmount()
}
//计算发票金额
const calculateTotalInvoiceAmount = () => {
    const total = selectedRows.value.reduce((sum, item) => {
        return sum + (parseFloat(item.thisOpen_amount) || 0);
    }, 0)
    invoiceForm.invoice_amount = total.toFixed(2)
}


// 检查所有选中单据的供应商是否一致
const checkSupplierConsistency = () => {
    if (selectedRows.value.length === 0) {
        return true
    }

    // 获取第一个单据的供应商信息
    const firstSupplierCode = selectedRows.value[0].supplier_code
    const firstSupplierName = selectedRows.value[0].supplier_name

    // 检查所有选中单据的供应商是否相同
    const inconsistentRows = selectedRows.value.filter(row =>
        row.supplier_code !== firstSupplierCode || row.supplier_name !== firstSupplierName
    )

    if (inconsistentRows.length > 0) {
        const inconsistentSuppliers = [...new Set(inconsistentRows.map(row => row.supplier_name))]
        ElMessage.error(`选中的单据供应商不一致！包含供应商：${firstSupplierName}、${inconsistentSuppliers.join('、')}`)
        return false
    }

    return true
}

// 准备提交数据 - 与实体类字段名完全匹配
const prepareSubmitData = () => {
    return selectedRows.value.map(row => {
        console.log("selectedRows",selectedRows.value)
        const thisOpenAmount = parseFloat(row.thisOpen_amount) || 0
        const noOpenAmount = parseFloat(row.noOpen_amount) || 0
        const validAmount = Math.min(thisOpenAmount, noOpenAmount)

        return {
            procurement_id: row.procurement_id,
            procurement_date: row.procurement_date,                    // 采购日期
            procurement_code: row.procurement_code,                    // 采购单号
            procurementOrder_code: row.procurementOrder_code,          // 关联订单号
            supplier_code: row.supplier_code,                          // 供应商编码
            supplier_name: row.supplier_name,                          // 供应商名称
            buyer: row.buyer,                                          // 采购员
            register_man: 'system',                                    // 登记人
            created_date: row.created_date,      // 创建日期
            procurement_quantity: parseInt(row.procurement_quantity) || 0, // 采购数量
            buy_amount: parseFloat(row.buy_amount) || 0,               // 采购金额
            tax_amount: parseFloat(row.tax_amount) || 0,               // 税额
            pay_amount: parseFloat(row.written_off_amount) || 0,               // 已付款
            pay_status: parseInt(row.pay_status) || 0,                 // 付款状态
            procurement_amount: parseFloat(row.procurement_amount) || 0, // 价税合计
            invoice_date: invoiceForm.invoice_date,                    // 开票日期
            invoice_amount: invoiceForm.invoice_amount,                               // 本次开票金额
            invoice_num: invoiceForm.invoice_num,                      // 发票号码
            alreadyOpen_amount: parseFloat(row.alreadyOpen_amount) || 0, // 已开票金额
            noOpen_amount: noOpenAmount,                               // 未开票金额
            thisOpen_amount: validAmount,                              // 本次开票金额（重复字段）
            remark: invoiceForm.remark || row.remark || '',            // 备注
            isDelete: 0                                                // 删除标志
            // invoice_title 字段需要特殊处理，如果是文件上传的话
        }
    })
}
// 发票登记
const handleInvoiceRegister = async () => {
    loading.value = true
    if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择登记的单据')
        loading.value = false
        return
    }
    if (invoiceForm.invoice_amount == 0) {
        ElMessage.warning('发票金额不能为0')
        loading.value = false
        return
    }
    if (invoiceForm.invoice_num == null || invoiceForm.invoice_num == '') {
        ElMessage.warning('发票号不能为空')
        loading.value = false
        return
    }
    // 检查供应商一致性
    if (!checkSupplierConsistency()) {
        return
    }
    const res = await axios.get(`/lxw/checkInvoice_num?invoice_num=${invoiceForm.invoice_num}`)
    if (res.data.code == 5500) {
        ElMessage.error(res.data.msg)
        loading.value = false
        return
    }
    try {
        // 准备提交数据 - 确保是数组格式
        const submitData = prepareSubmitData()
        console.log('提交的发票登记数据:', submitData)

        // 确保 submitData 是数组，不是对象
        if (!Array.isArray(submitData)) {
            ElMessage.error('数据格式错误，请重试')
            return
        }
        const res2 = await axios.post('/lxw/insert', submitData, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        if (res2.data.code == 5200) {
            ElMessage.info(res2.data.msg)
            // 清空选择 
            selectedRows.value = []
            // 重新加载数据
            getTableData()
            // 重置表单
            invoiceForm.invoice_date = ''
            invoiceForm.invoice_num = ''
            invoiceForm.remark = ''
        }
        else {
            ElMessage.error(res2.data.msg)
        }
    } catch (error) {
        console.error('发票登记失败:', error)
        ElMessage.error('发票登记失败，请重试')
    } finally {
        loading.value = false
    }
}

// 开票记录
const handleOpenRecord = () => {
    route.push({ name: 'procurementInvoice' })
}

// 导出
const handleExport = () => {
    alert('导出数据')
}

// 合计行方法
const getSummary = (param) => {
    const { columns, data } = param
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(val => !isNaN(val))) {
            sums[index] = ''
            return
        }
        const total = values.reduce((prev, curr) => prev + curr, 0)
        sums[index] = total.toFixed(2)
    })
    return sums
}
</script>

<style scoped>
.sales-product-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
}

.sales-product-form {
    max-width: 1400px;
}

.form-row {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    align-items: center;
}

.form-row .el-form-item {
    flex: 1;
    min-width: 330px;
    margin-bottom: 0;
}

.form-actions {
    margin: 16px 0;
    float: right;
    gap: 12px;
    display: flex;
}

/* 表单项样式 */
.el-form-item__label {
    font-weight: bold;
    color: #333;
}

.el-form-item__content {
    display: flex;
    align-items: center;
}

.el-input__inner,
.el-select .el-input__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
    border-color: #409eff;
    outline: none;
}

/* 底部开票信息区域 */
.footer-form {
    padding: 16px 20px;
    background-color: #f9f9f9;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-top: 20px;
}

/* 响应式 */
@media (max-width: 1000px) {
    .form-row {
        flex-direction: column;
    }

    .form-row .el-form-item {
        min-width: 100%;
    }

    .form-actions {
        float: none;
        justify-content: flex-start;
        margin-top: 20px;
    }
}

/* 退款行的红色字体样式 */
:deep(.el-table .refund-row) {
    color: #f56c6c;
}

:deep(.el-table .refund-row:hover > td) {
    background-color: #fef0f0 !important;
}

:deep(.el-table .refund-row .cell) {
    color: #f56c6c;
}
</style>